import * as mqtt from 'mqtt/dist/mqtt.min';
import {TopicFactory} from "./TopicFactory";
import PushPacket from "./tp/WebsocketTp";

class MqttClient {

  // username = "799893691@qq.com";
  // password = "123456";
  // clientId = "user.799893690@qq.com|timestamp=1712109418196,clientType=user,securemode=2,signmethod=hmacsha256|";

   constructor() {
    this.topicFactory = new TopicFactory();
    this.topicFactory.init();
    this.responseFutureMap = {};
  }

  close() {
    mqClient.disConnect();
  }

  setDataListener(dataListener) {
    this.dataListener = dataListener;
  }

  connect = () => {
	  console.log(12321321321321312321);
    let client = mqtt.connect('wss://'+this.addr+'/mqtt', {
      clientId: this.clientId, // 您的客户端ID
      username: this.username,  // 如果需要认证，请提供用户名
      password: this.password,   // 如果需要认证，请提供密码
      protocolVersion: 4, // 设置MQTT协议版本为5
    });

    console.log("连接mqtt", client);
    this.client = client;

    // 连接成功时的回调函数
    client.on('connect', function () {
      console.log('Connected to MQTT broker');
      !!this.dataListener && this.dataListener.onConnect(true);

      // setInterval(() => {
      //   // 发布消息
      //   client.publish('topic/example', 'Hello MQTT');
      // }, 1000);
    });

    let that = this;
    // 收到消息时的回调函数
    client.on('message', function (topic, message) {
      console.log('Received message:', message, 'on topic:', topic);
      that.handleMsg(topic, message);
    });

    // 处理错误
    client.on('error', function (error) {
      console.error('MQTT error:', error);
    });
  }

  ping = () => {
  }

  // 关闭WebSocket连接
  close = () => {
    this.client.close();
  }

  subscribe = (topics) => {
    // 订阅主题
    this.client.subscribe(topics, function (err) {
      if (!err) {
        console.log('Subscribed to', topics);
        !!this.dataListener && this.dataListener.onSubAck(true);
      } else {
        console.error("Subscribed fail", topics, err);
        !!this.dataListener && this.dataListener.onSubAck(false);
      }
    });

  }

  push = (qos, topic, msg) => {
    this.client.publish(topic, msg, {qos: qos});
    return true;
  }

  send(request, listener) {
    try {
      let topic = request.topic;
      console.log("send", request.mWrapperRequest);
      let msg = JSON.stringify(request.mWrapperRequest);
      // console.log(`发送数据\ntopic:${topic}\nmsg:${msg}`);

      let push = this.push(0, topic, msg);
      return push;
    } catch (e) {
      console.error(e, "发送mqtt数据失败");
    }

    return false;
  }

  sendResponse(response) {
    try {
      let topic = response.topic;
      let msg = JSON.stringify(response.mResponse);
      // console.log(`发送数据\ntopic:${topic}\nmsg:${msg}`);

      let push = this.push(0, topic, msg);
      return push;
    } catch (e) {
      console.error(e, "发送mqtt数据失败");
    }

    return false;
  }

  handleMsg = (topic, msg) => {
    try {
      console.log(`收到消息:${topic}, ${msg}`);

      // Call dataListener.onHandle method (assuming dataListener is defined elsewhere)
      !!this.dataListener && this.dataListener.onHandle(topic, msg);

      // Retrieve topic info from topicFactory
      let topicInfo = this.topicFactory.findThingTopic(topic);
      if (topicInfo) {
        let jsonObject = JSON.parse(msg);
        let fun = topicInfo.fun;
        let opAuth = topicInfo.opAuth;

        let response = null;
        let id = null;

        switch (fun) {
          case 'PropertyPost':
            if (opAuth === 'PUSH') {
              let payload = JSON.parse(msg);
              let params = jsonObject.params;
              payload.params = (params);
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
            } else if (opAuth === 'SUB') {
              let payload = JSON.parse(msg);
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
            }
            break;
          case 'PropertySet':
            if (opAuth === 'SUB') {
              let payload = JSON.parse(msg);
              let params = jsonObject.params;
              payload.params = (params);
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
            } else if (opAuth === 'PUSH') {
              let payload = JSON.parse(msg);
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
            }
            break;
          case 'EventPost':
            if (opAuth === 'PUSH') {
              let payload = JSON.parse(msg);
              let params = jsonObject.params;
              payload.params = (params);
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
            } else if (opAuth === 'SUB') {
              let payload = JSON.parse(msg);
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
            }
            break;
          case 'Service':
            if (opAuth === 'SUB') {
              let payload = JSON.parse(msg);
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onRequestSuccess(topic, payload);
            } else if (opAuth === 'PUSH') {
              let payload = JSON.parse(msg);
              let params = jsonObject.data;
              if (params) {
                payload.setData(params);
              }
              response = payload;
              id = payload.id;
              !!this.dataListener && this.dataListener.onResponseSuccess(topic, payload);
            }
            break;
        }

        if (id && response) {
          let responseFuture = this.responseFutureMap[id];
          if (responseFuture) {
            responseFuture.getListener().onSuccess(topic, response);
            delete this.responseFutureMap[id];
          }
        }
      }
    } catch (e) {
      console.error("处理mqtt收到的数据异常", e);
    }
  }

}

export default MqttClient;

